<template>
  <div class="home">
    <div class="body">
      <div class="buts">
        <el-button
          class="button-style"
          :class="selType == 'M' ? 'active' :''"
          type="primary"
          @click="changeType('M')"
        >面料上架</el-button>
        <el-button
          class="button-style"
          :class="selType == 'C' ? 'active' :''"
          type="primary"
          @click="changeType('C')"
        >裁片上架</el-button>
        <el-button
          class="button-style"
          :class="selType == 'F' ? 'active' :''"
          type="primary"
          @click="changeType('F')"
        >辅料上架</el-button>
        <el-button
          class="button-style"
          :class="selType == 'P' ? 'active' :''"
          type="primary"
          @click="changeType('P')"
        >成品上架</el-button>
      </div>
      <div class="cont">
        <el-row :gutter="20">
          <el-col :span="2" style="margin:1rem 0;">
            <div class="swiper-q" v-show="carouselArr.length>0"></div>
            <swiper :options="swiperOption" class="swiper-w" ref="mySwiper">
              <swiper-slide class="swiper-slide" v-for="(item,index) in carouselArr" :key="index">
                <!-- <img :src="item" /> -->
                {{item.NodeName}}
              </swiper-slide>
            </swiper>
          </el-col>
          <el-col :span="22">
            <div class="arbitrage-w">
              <table border="1" cellspacing="1" v-html="tableDom">
                <tbody></tbody>
              </table>
            </div>
            <div class="block-w">
                <div class="block" v-for="(item,index) in materielList.slice((currentPage - 1) * pageSize, currentPage * pageSize)" :class="item.materielID === materielID ? 'active' : ''" :key="index" @click="selectDetail(item)">
                    <div class="line">厂家：{{item.CustomerName}}</div>
                    <div class="line">物料：{{item.MaterielClassName}}</div>
                    <div class="line">
                        <div class="row">数量：{{item.TotalCount}}</div>
                        <div class="row">重量：{{item.TotalWeight}}</div>
                    </div>
                </div>
            </div>
            <div>
                <el-pagination v-if="totalCount/pageSize>1"
                    background
                    layout="prev, pager, next"
                    :total="totalCount"
                    :current-page.sync="currentPage"
                    :page-size="pageSize"
                    @current-change="changePage()"
                    style="margin:20px 0;"
                ></el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import Mixin from '@/components/mixin'
import {getArbitrage, getCarouselArr, getMaterielList, getHouseMaterielsByShelf, offShelf, changeShelf, deleteShelf} from '@/api/materiel' // 接口
export default {
  name: 'demo',
  data () {
    return {
      materielList: [],
      materielID: '',
      carouselArr: [],
      swiperOption: {
        // 垂直操作
        direction: 'vertical',
        // 每页显示个数
        slidesPerView: 7,
        // 自动轮播
        autoplay: {
          delay: 2000,
          // 当用户滑动图片后继续自动轮播
          disableOnInteraction: false
        },
        // 开启循环模式
        loop: false,
        // 手形
        grabCursor: true,
        centeredSlides: true,
        observer: true,
        observeParents: true,
        notNextTick: true,
        height: 500,
        on: {
          // 使用es6的箭头函数，使this指向vue对象
          slideChangeTransitionStart: (dom) => {
            this.realIndex = dom.realIndex
            this.getArbitrage()
          }
        }
      },
      selType: 'M',
      tableDom: '',
      dragIndex: 0,
      arbitrage: {},
      dragType: 0, // 0:上架（右侧表移入） 1：修改（中间表内移动）
      oldHouseFlnkID: '',
      realIndex: 0,
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      tempStockPlaceID: '',
      isDel: false
    }
  },
  computed: {
  },
  components: {
  },
  mixins: [Mixin], // demo.vue 中声明minix 进行混合
  methods: {
    // 修改table tr行的背景色
    tableRowStyle ({ row, rowIndex }) {
      return {
        backgroundColor: 'rgb(0, 63, 140)',
        color: '#fff',
        fontWeight: 'bold',
        height: '0.7rem',
        fontSize: '15px'
      }
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: rgb(0, 63, 140);color: #fff;font-weight: bold;height:0.7rem;font-size:15px'
      }
    },
    selectDetail (item) {
      let vm = this
      if (item) {
        vm.materielID = item.materielID
        if (vm.tempStockPlaceID !== '') {
          if (vm.materielID === '') {
            vm.$message('请选贼库位')
            return
          }
          vm.$("td[StockPlaceID='" + vm.tempStockPlaceID + "']").attr('shelfflnkid')
          vm.arbitrage = {
            ShelfFlnkID: vm.$("td[StockPlaceID='" + vm.tempStockPlaceID + "']").attr('shelfflnkid'),
            HouseFlnkID: vm.$("td[StockPlaceID='" + vm.tempStockPlaceID + "']").attr('stockplaceid')
          }
          vm.saveShelf()
          vm.getArbitrage()
        }
      }
    },
    // 渲染table dom
    getGoodKWLocation (data) {
      let vm = this
      // 根据货架标识读取库位列表
      vm.tableDom = ''
      var htmlTr = ''
      if (data != null) {
        var dataList = data.GoodKWLocation
        for (let i = 1; i <= data.MaxLineID + 1; i++) {
          let _temp =
            data.MaxLineID - i + 1 === 0
              ? ''
              : data.MaxLineID - i + 1 + '层'
          if (_temp === '') { htmlTr += '<tr style="height:35px;"><td>' + _temp + '</td>' } else { htmlTr += '<tr><td>' + _temp + '</td>' }
          for (let j = 1; j <= data.MaxColumnID; j++) {
            if (data.MaxLineID === i - 1) {
              htmlTr += '<td>' + j + '</td>'
            }
            var tdItemList = dataList.filter((_item) => {
              return _item.LineID === i && _item.ColumnID === j
            })

            if (tdItemList != null && tdItemList.length > 0) {
              htmlTr +=
                '<td onclick="changeBorder(this)" StockPlaceID="' +
                tdItemList[0].StockPlaceID +
                '"ShelfFlnkID="' +
                tdItemList[0].ShelfFlnkID +
                '" class="tdBody" style="' +
                (tdItemList[0].RowSpan > 1 || tdItemList[0].ColSpan > 1
                  ? 'background-color:#00438a;'
                  : '') +
                '" isselected="0" floorid="' +
                tdItemList[0].FloorID +
                '" colid="' +
                tdItemList[0].ColID +
                '" lineid="' +
                tdItemList[0].LineID +
                '" columnid="' +
                tdItemList[0].ColumnID +
                '" rowspan="' +
                tdItemList[0].RowSpan +
                '" colspan="' +
                tdItemList[0].ColSpan +
                '"ondragover="allowDrop(event)"' +
                'ondrop="selectTd(this);">' +
                tdItemList[0].FloorID +
                '-' +
                tdItemList[0].ColID +
                '</td>'
            }
          }
          htmlTr += '</tr>'
        }
      }
      vm.tableDom = htmlTr
      if (vm.carouselArr.length > 0) {
        vm.setArbitrage(vm.carouselArr[vm.realIndex].FlnkID)
      }
      vm.rowDrop()
    },
    getCarouselArr () {
      let vm = this
      let params = new FormData()
      params.append('WarehouseFlnkID', vm.warehouseFormat(vm.selType))
      params.append('MaterielTypeCode', vm.selType)
      getCarouselArr(params).then((response) => {
        if (response.data.data) {
          vm.carouselArr = response.data.data
          vm.getArbitrage()
        }
      })
    },
    changeType (type) {
      let vm = this
      vm.selType = type
      vm.getCarouselArr()
      vm.getMaterielList()
      vm.realIndex = 0
      vm.$refs.mySwiper.swiperInstance.slideTo(0)
    },
    getArbitrage () {
      let vm = this
      let params = new FormData()
      if (vm.carouselArr.length === 0) {
        vm.getGoodKWLocation([])
        return
      }
      params.append('ShelfFlnkID', vm.carouselArr[vm.realIndex].FlnkID)
      getArbitrage(params).then((response) => {
        if (response.data) {
          vm.getGoodKWLocation(response.data)
        }
      })
    },
    selectTd (dom) {
      let vm = this
      if (vm.dragType) {
        // 拖动是原来的就return
        if (vm.oldHouseFlnkID === dom.getAttribute('stockplaceid')) {
          return
        }
        vm.changeShelf(dom.getAttribute('stockplaceid'))
        // 把之前的要清掉（？？？这里重新渲染不会清拖动之前的？？？）
        let _temp = document.querySelector(
          ".arbitrage-w tbody tr td[stockplaceid='" + vm.oldHouseFlnkID + "']"
        )
        if (_temp) {
          _temp.innerHTML =
            _temp.getAttribute('floorid') +
            '-' +
            _temp.getAttribute('columnid')
          _temp.style.backgroundColor = ''
        }
      } else {
        vm.arbitrage = {
          ShelfFlnkID: dom.getAttribute('shelfflnkid'),
          HouseFlnkID: dom.getAttribute('stockplaceid')
        }
        vm.saveShelf()
      }
    },
    // 根据物料类型读取待货区仓库中物料列表
    getMaterielList () {
      let vm = this
      let params = new FormData()
      params.append('WarehouseFlnkID', vm.warehouseFormat(vm.selType))
      params.append('Type', vm.selType)
      getMaterielList(params).then((response) => {
        if (response.data.result) {
          vm.materielList = response.data.data
        //   var obj = response.data.data[0]
        //   for (var i = 0; i < 31; i++) {
        //     vm.materielList.push(obj)
        //   }
          vm.totalCount = vm.materielList.length
          var id = 0
          vm.materielList.forEach(element => {
            element.materielID = id
            id++
          })
        }
      })
    },
    changePage () {
        // var vm=this
    },
    // 往table里面渲染数据
    setArbitrage (flnkID) {
      let vm = this
      let params = new FormData()
      params.append('ShelfFlnkID', flnkID)
      getHouseMaterielsByShelf(params).then((response) => {
        if (response.data.result) {
          response.data.data.map((item) => {
            let td = `
              <p style="font-size:12px">${item.CustomerName}</p>
              <p style="font-size:12px">${item.StyleName}</p>
              <p style="font-size:12px">${item.MaterielClassName}</p>
              `
            let dom = document.querySelector(
                ".arbitrage-w tbody tr td[stockplaceid='" +
                  item.WarehouseKWFlnkID +
                  "']"
              )
            if (dom !== null) {
              if (item.Tag === 0) {
                td += `<p class="el-icon-close close" onclick="delShelf('${item.WarehouseKWFlnkID}')"></p>`
                dom.innerHTML = td
                dom.setAttribute('draggable', true)
                dom.ondragstart = function () {
                  vm.dragTd(item.WarehouseKWFlnkID)
                }
                dom.style.backgroundColor = 'rgb(242, 242, 242,0.5)'
              }
              if (item.Tag === 1) {
                dom.innerHTML = td
                dom.setAttribute('draggable', true)
                dom.ondragstart = function () {
                  vm.dragTd(item.WarehouseKWFlnkID)
                }
                dom.style.backgroundColor = 'rgb(255,0,0,0.8)'
              }
              if (item.Tag === 2) {
                dom.innerHTML = td
                dom.setAttribute('draggable', true)
                dom.ondragstart = function () {
                  vm.dragTd(item.WarehouseKWFlnkID)
                }
              }
            }
          })
        }
      })
    },
    // 右侧拖拽
    rowDrop () {
      let vm = this
      const rightTbody = document.querySelectorAll(
        // '.el-table__body-wrapper tbody tr'
        '.block-w .block'
      )
      vm.$(rightTbody).each(function (index) {
        vm.$(this)[0].setAttribute('draggable', true)
        vm.$(this)[0].ondragstart = function () {
          vm.drag(index)
        }
      })
    },
    allowDrop (ev) {
      ev.preventDefault()
    },
    drag (index) {
      let vm = this
      vm.dragType = 0
      vm.dragIndex = index
    },
    dragTd (oldHouseFlnkID) {
      let vm = this
      vm.dragType = 1
      vm.oldHouseFlnkID = oldHouseFlnkID
    },
    // 上架
    saveShelf () {
      let vm = this
      if (vm.materielList.length > 0) {
        let params = {
          BarCode: vm.materielList[vm.dragIndex].BarCode,
          TaskType: 1,
          ShelfFlnkID: vm.arbitrage.ShelfFlnkID,
          HouseFlnkID: vm.arbitrage.HouseFlnkID,
          TotalCount: Math.ceil(vm.materielList[vm.dragIndex].TotalCount),
          TotalWeight: vm.materielList[vm.dragIndex].TotalWeight
        }
        offShelf(params).then((response) => {
          if (response.data.result) {
          // vm.changeType(vm.selType)
            vm.getMaterielList()
          } else {
            vm.$message(response.data.error)
          // vm.changeType(vm.selType)
          }
        })
      }
    },
    // 修改上架
    changeShelf (newHouseFlnkID) {
      let vm = this
      let params = new FormData()
      params.append('OldHouseFlnkID', vm.oldHouseFlnkID)
      params.append('NewHouseFlnkID', newHouseFlnkID)
      changeShelf(params).then((response) => {
        if (response.data.result) {
          // vm.changeType(vm.selType)
          vm.getMaterielList()
        } else {
          vm.$message(response.data.error)
          // vm.changeType(vm.selType)
        }
      })
    },
    // 撤销上架
    delShelf (houseFlnkID) {
      let vm = this
      vm.$('.arbitrage-w table tr td').css('border', '')
      event.stopPropagation()
      let params = new FormData()
      params.append('HouseFlnkID', houseFlnkID)
      deleteShelf(params).then((response) => {
        if (response.data.result) {
          vm.$("td[stockplaceid='" + vm.tempStockPlaceID + "']").css('border', '')
          vm.tempStockPlaceID = ''
          vm.oldHouseFlnkID = ''
          vm.dragIndex = 0
          vm.materielID = ''
          // vm.changeType(vm.selType)
          vm.getMaterielList()
            // 把之前的要清掉（？？？这里重新渲染不会清拖动之前的？？？）
          let _temp = document.querySelector(
              ".arbitrage-w tbody tr td[stockplaceid='" + houseFlnkID + "']"
            )
          if (_temp) {
            _temp.innerHTML =
                _temp.getAttribute('floorid') +
                '-' +
                _temp.getAttribute('columnid')
            _temp.style.backgroundColor = ''
          }
        } else {
          vm.$message(response.data.error)
          // vm.changeType(vm.selType)
        }
      })
    },
    changeBorder (dom) {
      // 判断是否有边框样式
      let vm = this
      vm.tempStockPlaceID = dom.getAttribute('stockplaceid')
      vm.oldHouseFlnkID = dom.getAttribute('stockplaceid')
      // 判断是否有物料
      if (vm.$("td[stockplaceid='" + vm.tempStockPlaceID + "'] p").length > 0) {
        vm.$message('已存在上架物料')
        return
      }
      // 清空所有边框
      vm.$('.arbitrage-w table tr td').css('border', '')
      if (vm.$(dom).css('border').indexOf('solid') > -1) {
        vm.$(dom).css('border', '')
        vm.dragIndex = 0
        vm.dragType = 0
      } else {
        vm.$(dom).css('border', 'solid 2px #ff6600')
        // 获取选中的边框序号
        if (vm.materielID === '') {
          vm.$message('请选择物料')
          return
        }
        vm.materielList.forEach(function (item, index) {
          if (vm.materielID === item.materielID) {
            vm.dragIndex = index
            return
          }
        })
        vm.dragIndex = 0
        vm.selectTd(dom)
        vm.getArbitrage()
        vm.materielID = ''
      }
    }
  },
  watch: {
  },
  mounted () {
    let vm = this
    // this.swiper.slideTo(0)
    vm.getCarouselArr()
    window.selectTd = vm.selectTd // 绑定dom原生onclick方法到vue对象方法
    window.allowDrop = vm.allowDrop // 绑定dom原生onclick方法到vue对象方法
    window.delShelf = vm.delShelf // 绑定dom原生onclick方法到vue对象方法
    window.changeBorder = vm.changeBorder  // 绑定dom原生onclick方法到vue对象方法
    vm.getMaterielList()
    clearInterval(vm.setInterval)
    vm.setInterval = setInterval(() => {
      vm.setArbitrage(vm.carouselArr[vm.realIndex].FlnkID)
      vm.rowDrop()
      vm.getMaterielList()
    }, 5000)
  },
  beforeDestroy: function () {
    let vm = this
    clearInterval(vm.setInterval)
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
@import "~@/css/materiel/onShelf.scss";
</style>
